package mysql

import (
	"gorm.io/gorm"
	"video-hub/videorpc/videorpc"
)

type Video struct {
	gorm.Model
	UserId        int    `gorm:"type:int(11);comment:用户Id"`
	VideoTitle    string `gorm:"type:varchar(30);comment:视频标题"`
	VideoCategory string `gorm:"type:varchar(30);comment:视频分类"`
	VideoStatus   int    `gorm:"type:int(11);comment:视频状态"`
	Num           int    `gorm:"type:int(11);comment:视频播放量"`
	Url           string `gorm:"type:varchar(255);comment:视频"`
	VideoIntro    string `gorm:"type:varchar(30);comment:视频简介"`
	LikeNum       int    `gorm:"type:int;default 0;comment:点赞数量"`
	CollectNum    int    `gorm:"type:int(11);default 0;comment:收藏数量"`
	CommentNum    int    `gorm:"type:int(11);default 0;comment:评论数量"`
	ReleaseTime   string `gorm:"type:varchar(30);comment:发布时间"`
	TopicId       int    `gorm:"type:int(11);comment:话题Id"`
}

func (v *Video) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(v).Error
}

func (v *Video) UpdateVideo(db *gorm.DB) error {
	return db.Debug().Updates(v).Error
}

func (v *Video) FindVideoId(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).First(v).Error
}

func (v *Video) VideoDel(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Delete(v).Error
}

func (v *Video) UpdateNum(db *gorm.DB, id int64) error {
	return db.Debug().Model(v).Where("id=?", id).Update("videos.num", gorm.Expr("videos.num+?", 1)).Error
}

func (v *Video) UdateNums(db *gorm.DB, id uint) error {
	return db.Debug().Model(v).Where("id=?", id).Update("videos.collect_num", gorm.Expr("videos.collect_num-?", 1)).Error
}
func VideoList(db *gorm.DB, in *videorpc.VideoListRequest) ([]*videorpc.VideoList, error) {
	var list []*videorpc.VideoList
	//SELECT
	//  users.url,
	//  video_title,
	//  nick_name,
	//  num
	//FROM
	//  videos
	//  LEFT JOIN users ON videos.user_id = users.id
	tx := db.Debug().Model(&Video{}).Select(
		"users.url as url",
		"video_title",
		"nick_name",
		"num",
	).Joins("LEFT JOIN users ON videos.user_id = users.id")
	if in.SortType == 0 {
		tx.Order("num desc")
	}
	if in.SortType == 1 {
		tx.Order("videos.created_at desc")
	}
	tx.Scopes(Paginate(int(in.Page), int(in.Size))).
		Find(&list)
	return list, err

}
func VideoAndUserAndTopic(db *gorm.DB, id int64) (videorpc.VideoAndUserAndTopicResponse, error) {
	var video videorpc.VideoAndUserAndTopicResponse
	//SELECT
	//  video_title,
	//  video_intro,
	//  num,
	//  nick_name,
	//  users.url,
	//  topic_name
	//FROM
	//  videos
	//  LEFT JOIN users ON videos.user_id = users.id
	//  LEFT JOIN topics ON videos.topic_id = topics.id
	db.Debug().Model(&Video{}).Select(
		"video_title",
		"video_intro",
		"num",
		"nick_name",
		"users.url",
		"topic_name",
	).Joins("LEFT JOIN users ON videos.user_id = users.id").
		Joins("LEFT JOIN topics ON videos.topic_id = topics.id").Where("videos.id=?", id).First(&video)
	return video, err

}
